;(function() {

	requirejs(['jquery', 'angular', 'uiBootstrap', '/esvml/web/goods/js/responsive.js'], function($, angular) {

		var app = angular.module('app', ['ui.bootstrap']);

		app.factory('safeApply', ['$rootScope', function($rootScope) {//apply
		    return function(scope, fn) {
		        var phase = scope.$root.$$phase;
		        if (phase == '$apply' || phase == '$digest') {
		            if (fn && ( typeof (fn) === 'function')) fn();
		        } else {
		            scope.$apply(fn);
		        }
		    }
		}])

		.controller('storeGoods', ['$scope', '$timeout', 'safeApply', '$http', function($scope, $timeout, safeApply, $http) {

			$scope.loading = false;//loading开关

			$scope.norms = {
				id: $('.goods .inner .info').attr('pdtid'),
				can: {},//可行规格
				selSKU: {},//已选集合
				num: 0,//当前规格选择数量
				nowSKU: {
					color: '',
					size: ''
				},//当前选择
				allSKU: {
					color: [],
					size: []
				},
				stock: 0,//每个规格库存
				selTips: true,//采购清单为空提示
				price: JSON.parse($('.right .order-num').attr('data')),//价格区间
				pLen: JSON.parse($('.right .order-num').attr('data')).length,
				isMix: 1,//是否混批,1是0不是
				totalNum: 0,//总计数量
				totalPrice: 0//总价
			}

			$scope.seline = 0;

			$scope.tab2 = {//tab-2页
				pageNum: 10,//默认1页,这里数字需要X10
				currentPage: 1,//当前页数
				maxSize: 5,//分页个数
				hits: 15,//每个分页显示列表数量
				isLoad: false//是否已加载
			};

			$scope.tab3 = {//tab-3页
				pageNum: 10,//默认1页,这里数字需要X10
				currentPage: 1,//当前页数
				maxSize: 5,//分页个数
				hits: 25,//每个分页显示列表数量
				isLoad: false//是否已加载
			};

			var norms = $scope.norms;

			var lineW = norms.isMix=='1'?'totalNum':'num';//价格区间红横线监控

			$scope.$watch('norms.' + lineW, function(val) {

				if(norms.price[2] && parseInt(val) > parseInt(norms.price[2].qty))
					$scope.seline = {top: '90px'};

				else if(norms.price[1] && parseInt(val) > parseInt(norms.price[1].qty)) 
					$scope.seline = {top: '60px'};

				else
					$scope.seline = {top: '30px'};
				
				safeApply($scope);
			});

			var canSKU = $('.right .sku-list').attr('data').split(',');
			for(var i in canSKU) {

				norms.can[canSKU[i]] = true;
				if(norms.allSKU.color.indexOf(canSKU[i].split('|')[0]) == -1)
					norms.allSKU.color.push(canSKU[i].split('|')[0]);

				if(norms.allSKU.size.indexOf(canSKU[i].split('|')[1]) == -1)
					norms.allSKU.size.push(canSKU[i].split('|')[1]);
			}//获取可行规格,画出存在的规格

			$scope.numCheck = function() {//数量纠正


				norms.num = norms.num.replace(/\D/gi,'') != '' ?
									parseInt(norms.num.replace(/\D/gi,'')): 0;

				if(parseInt(norms.num) >= norms.stock)
					norms.num = norms.stock;

				if(norms.nowSKU.color == '' || norms.nowSKU.size == '' || norms.stock == 0) {
					alert('颜色尺寸未选择或库存为0');
					norms.num = 0;
					return false;
				}

				$scope.setCartList();
			}

			$scope.numAct = function(opt) {//数量控制

				if(norms.nowSKU.color == '' || norms.nowSKU.size == '' || norms.stock == 0) {
					alert('颜色尺寸未选择或库存为0');
					norms.num = 0;
					return false;
				}
				if(opt == 'add') {

					if(norms.stock > 0 && parseInt(norms.num) < norms.stock)
						norms.num = parseInt(norms.num) + 1;
				}//add

				if(opt == 'sub') {

					if(norms.stock > 0 && parseInt(norms.num) > 0)
						norms.num = parseInt(norms.num) - 1;
				}//sub

				$scope.setCartList();
			}

			$scope.setCartList = function (key) {

				if(key)//清单删除
					if(norms.selSKU[key]) {

						if(norms.nowSKU.color == norms.selSKU[key].color)
							norms.num = 0;
						delete norms.selSKU[key];
					}

				var arr = [];
				arr.push(norms.nowSKU.color, norms.nowSKU.size);

				if(norms.num > 0)
					norms.selSKU[arr.join('|')] = {
						color: norms.nowSKU.color,
						num: parseInt(norms.num),
						size: norms.nowSKU.size
					};
				else if(norms.selSKU[arr.join('|')])
					delete norms.selSKU[arr.join('|')];

				norms.selTips = true;

				var totalNum = 0, totalPrice = 0, oldP = 0, nowP = 0;

				for(var i in norms.selSKU) {//统计数量

					norms.selTips = false;
					totalNum += parseInt(norms.selSKU[i].num);
				}
 				norms.totalNum = totalNum;

				for(var i in norms.selSKU) {//判断价格

					norms.selSKU[i].price = norms.price[0]['pro_price'] ?
															norms.price[0]['pro_price'] : norms.price[0].price;

					if(norms.isMix == '1') {//混批计算

						if(norms.pLen > 1 && norms.totalNum > norms.price[1].qty) {

							norms.selSKU[i].price = norms.price[1]['pro_price'] ?
															norms.price[1]['pro_price'] : norms.price[1].price;
						}

						if(norms.pLen > 2 && norms.totalNum > norms.price[2].qty) {

							norms.selSKU[i].price = norms.price[2]['pro_price'] ?
															norms.price[2]['pro_price'] : norms.price[2].price;
						}
					} else {//不能混批

						if(norms.pLen > 1 && norms.selSKU[i].num > norms.price[1].qty) {

							norms.selSKU[i].price = norms.price[1]['pro_price'] ?
															norms.price[1]['pro_price'] : norms.price[1].price;
						}

						if(norms.pLen > 2 && norms.selSKU[i].num > norms.price[2].qty) {

							norms.selSKU[i].price = norms.price[2]['pro_price'] ?
															norms.price[2]['pro_price'] : norms.price[2].price;
						}
					}

					totalPrice += norms.selSKU[i].num * norms.selSKU[i].price;
				}

				norms.totalPrice = totalPrice;//总价

				safeApply($scope);
			}

			$scope.setSKU = function(name, sku) {

				if(name == 'color') {

					var size = norms.allSKU.size;

					for(var i=0;i<size.length;i++) {

						var arr = [];
						arr.push(sku, size[i]);
						if(!norms.can[arr.join('|')]) {
							$('.right .sku-list button.size').eq(i).attr('disabled', 'disabled');
						}
					}
				}//color

				if(name == 'size') {

					var color = norms.allSKU.color;

					for(var i=0;i<color.length;i++) {

						var arr = [];
						arr.push(color[i], sku);
						if(!norms.can[arr.join('|')]) {
							$('.right .sku-list button.color').eq(i).attr('disabled', 'disabled');
						}
					}
				}//size

				if(norms.nowSKU.color != '' && norms.nowSKU.size != '') {

					var arr = [];
					arr.push(norms.nowSKU.color, norms.nowSKU.size);

					if(norms.selSKU[arr.join('|')]) {

						norms.num = norms.selSKU[arr.join('|')].num;
						safeApply($scope);
					}

					$http({
						method: 'POST',
						url: '/control/pub/command',
						params: {
							'command': "com.jackrain.ds.CommESGoodsStorageQuerypub",
							'SPEC1': norms.nowSKU.color,
							'SPEC2': norms.nowSKU.size,
							'ES_GOODS_ID': norms.id,
							'getjson': true,
						}
					}).then(function(res) {
						
						if(res.data.code == 0)
							norms.stock = res.data.spdata[0].QTY;
						else
							norms.stock = 0;
					}, function(res) {

						if(!res.data) {

							alert('获取库存失败,请稍候重试');
							norms.stock = 0;
							return false;
						}
					});
				}
			}
			
		}])
		.directive('sku', ['safeApply', function(safeApply) {
			return {
				restrict: 'A',
				scope: true,
				link: function(scope, el, attrs) {

					var name = attrs.sku.split('|')[0];
					var sku = attrs.sku.split('|')[1];

					el.on('click', function() {
						
						if(el.attr('disabled') == 'disabled') return false;

						$(this).children('button').toggleClass('active');
						$(this).siblings('a').children('button').removeClass('active');

						scope.$parent.norms.num = 0;//把之前选择的数量重置
						scope.$parent.norms.stock = 0;

						safeApply(scope.$parent);
						$('.right .sku-list button.'+ (name=='color'?'size':'color')).removeAttr('disabled');
						if($(this).children('button').hasClass('active')) {
							scope.$parent.norms.nowSKU[name] = sku;
							scope.$parent.setSKU(name, sku);
						} else {
							
							scope.$parent.norms.nowSKU[name] = '';
							return false;
						}
					});
				}
			}
		}]);

		angular.element(document).ready(function() {
			angular.bootstrap(document, ['app']);
		});
		
		return app;
	});
})();